<template>
  <div style="width: 800px; margin: auto">
    <h1>登录页面</h1>
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
    >
      <el-form-item label="账号" prop="userName">
        <el-input v-model="ruleForm.userName" />
      </el-form-item>
      <el-form-item label="密码" prop="userPass">
        <el-input v-model="ruleForm.userPass" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          登录
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">Reset</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { loginService } from "../api/api";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
const router = useRouter();
const ruleFormRef = ref<FormInstance>();
const ruleForm = ref({
  userCode: "",
  userMobile: "",
  userName: "",
  userPass: "",
});

const locationOptions = ["Home", "Company", "School"];

const rules = reactive<FormRules>({
  userName: [
    { required: true, message: "账号不能为空", trigger: "blur" },
    { min: 3, max: 6, message: "账号长度必须3-6位", trigger: "blur" },
  ],
  userPass: [
    { required: true, message: "密码不能为空", trigger: "blur" },
    {
      pattern: /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[a-zA-Z0-9]{6,}$/,
      message: "密码必须包含字母数字,最少6位",
      trigger: "blur",
    },
  ],
});

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      loginService(ruleForm.value).then((res) => {
        if (res.data.code == 200) {
          let user = res.data.data;
          let token = user.token;
          window.sessionStorage.setItem("token", token);
          window.sessionStorage.setItem("user", JSON.stringify(user));
          ElMessage.success("登录成功");
          router.push("/home");
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

const options = Array.from({ length: 10000 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}));
</script>
